#include <iostream>
#include "field.h"
#include "capp.h"

Field :: Field () {
};

void Field::Draw(SDL_Surface* Surf_Display) {
  if(Surf_Display == NULL) return;

  for(int Y = 0;Y < MAP_HEIGHT;Y++) {
    for(int X = 0;X < MAP_WIDTH;X++) { 
      Surface::Draw(surf_tileset, (cellBg[X][Y]) * TILE_SIZE, 0, TILE_SIZE, TILE_SIZE, Surf_Display, X*TILE_SIZE + FIELD_BORDER, Y*TILE_SIZE + FIELD_BORDER);   
    }
  }
};

bool Field::Load(char* File) {
  surf_tileset = Surface::Load("../gfx/field.bmp");
  //TileList.clear();

  FILE* FileHandle = fopen(File, "r");

  if(FileHandle == NULL) {
    return false;
  }

  for(int Y = 0;Y < MAP_HEIGHT;Y++) {
    for(int X = 0;X < MAP_WIDTH;X++) {
      fscanf(FileHandle, "%d ", &cellBg[X][Y]);
      cellEntity[X][Y] = NULL;
    }
    fscanf(FileHandle, "\n");
  }
  
  fclose(FileHandle);
  
  for (int i = 0; i < Entity::EntityList.size(); i++){
    if(!Entity::EntityList[i]){
      continue;
    }
    std::cout << "Some entity on the list :: " << Entity::EntityList[i]->cellX << "," << Entity::EntityList[i]->cellY << "\n";
    cellEntity[Entity::EntityList[i]->cellX][Entity::EntityList[i]->cellY] = Entity::EntityList[i];
  }

  return true;
}

Field :: ~Field(){
    delete surf_tileset;
};

void Field::OnLButtonDown(int mX, int mY){
  switch(CApp::turnState){
    case PLAYER_IDLE:
      std::cout << "PLAYER_IDLE:" << std::endl;
      if(mX > FIELD_BORDER && mX < TILE_SIZE * MAP_WIDTH + FIELD_BORDER) {
        if(mY > FIELD_BORDER && mY < TILE_SIZE * MAP_HEIGHT + FIELD_BORDER) {
          std::cout << "GAMEFIELD: LMB on cell ";
          int cX, cY; // mouse coordinates in gamefield cells
          cX = (mX - FIELD_BORDER) / TILE_SIZE;
          cY = (mY - FIELD_BORDER) / TILE_SIZE;
          if(cellEntity[cX][cY] != NULL){
            std::cout << "Someone's on this cell!" << std::endl;
          }
          std::cout << cX << "," << cY << std::endl;
        }
      }
      break;
    case PLAYER_MOVE:
      std::cout << "PLAYER_MOVE:" << std::endl;
      break;
    case PLAYER_THROW:
      std::cout << "PLAYER_THROW:" << std::endl;
      break;
  }
  break;
  case PLAYER_MOVE:
  
  break;
  
  case PLAYER_THROW:
  
  break;
  }
};
// vector<Entity*>::iterator itr = Entity::EntityList.begin();
// while(itr != Entity::EntityList.end()){
// if(Ent)
// ++itr;
// }
